package com.rbcs.reimb.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rbcs.borrow.model.Borrow;
import com.rbcs.flow.FlowConstants;
import com.rbcs.flow.service.FlowManager;
import com.rbcs.reimb.model.Reimb;
import com.rbcs.reimb.model.ReimbDetail;
import com.rbcs.repay.RePayConstants;
import com.rbcs.repay.model.RePay;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.ApplicationException;
import com.systop.core.service.BaseGenericsManager;
import com.systop.core.util.DateUtil;

/**
 * 报销申请管理Manager
 * 
 * @author ShangHua
 */
@Service
public class ReimbManager extends BaseGenericsManager<Reimb> {

	//流程管理Manager
	@Autowired
	private FlowManager flowManager;
	
	/**
	 * 报销明细管理Manager
	 */
	@Autowired
	private ReimbDetailManager reimbDetailManager;
	
	/**
	 * 保存报销申请单
	 * @param reimb
	 * @param list
	 */
	@Transactional
	public void save(Reimb reimb, List<ReimbDetail> list) {
		if (getDao().exists(reimb, "singleNo")) {
			if (StringUtils.isNotEmpty(reimb.getSingleNo())) {
				throw new ApplicationException("报销申请单号为【" + reimb.getSingleNo() + "】的记录已存在。");
			}
		}
		try {
			// 如果是修改就先删除旧的，再保存新的
			if (reimb.getId() != null && reimb.getId() > 0) {
				del(reimb.getId());
			}
			super.save(reimb);
			// 保存报销明细详单
			for (ReimbDetail rd : list) {
				reimbDetailManager.save(rd);
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException("保存失败");
		}

	}
	
	/**
	 * 删除报销申请主表以及相关联的详单信息
	 * @param reimb
	 */
	@Transactional
	public void reimbRemove(Reimb reimb) {
		try {
			if (reimb.getId() != null && reimb.getId() > 0) {
				if (reimb.getChildReimbs().size() > 0 ) {
					for (Reimb childReimb : reimb.getChildReimbs()) {
						del(childReimb.getId());
						this.remove(childReimb);
					}
				} else {
					del(reimb.getId());	
				}
			}
			this.remove(reimb);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException("删除失败");
		}
	}
	
	/**
	 * 父报销单下的子报销单的审批信息
	 * @param reimbId
	 */
	@Transactional
	public void saveParentReimb(Integer parentReimbId, String audStutus) {
		Reimb parentReimb = this.get(parentReimbId);
		if (audStutus.equals(FlowConstants.AUDIT_PASS)) {
			int maxSize = parentReimb.getChildReimbs().size();
			List<Reimb> childList = query("from Reimb r where r.parentReimb.id = ? and r.audStatus = ? ", 
				  new Object[] {parentReimbId, FlowConstants.AUDIT_PASS});
			if (maxSize == childList.size()) {
				parentReimb.setAudStatus(FlowConstants.AUDIT_PASS);
			  this.save(parentReimb);
			}
		} else {
			parentReimb.setAudStatus(FlowConstants.AUDIT_NOPASS);
		  this.save(parentReimb);
		}
	}
	
	/**
	 * 保存流程表
	 * @param borrow
	 */
	@Transactional
	public void saveFlows(Reimb reimb) {
		if (reimb != null) {
			//设置报销单的审批状态为"待审批"
			reimb.setAudStatus(FlowConstants.AUDIT_PENDING);
			getDao().saveOrUpdate(reimb);
			flowManager.createReimbFlow(reimb);
		}
	}
	
	/**
	 * 查询报销单
	 * @param reimbId
	 */
	public void del(Integer reimbId) {
		List<ReimbDetail> detailList = reimbDetailManager.query(
				"from ReimbDetail rd where rd.reimb.id = ?", reimbId);
		for (ReimbDetail rd : detailList) {
			reimbDetailManager.remove(rd);
		}
	}
	
	/**
	 * 保存报销出纳付款的信息
	 */
	@Transactional
	public void paySave(Reimb reimb, User auditor) {
		if (reimb == null) {
			return;
		}
		save(reimb);
		
    if (StringUtils.isNotBlank(reimb.getTotalBorrowIds())) {
    	String[] totalBorrowIds = reimb.getTotalBorrowIds().split(",");
    	for (int i=0; i < totalBorrowIds.length; i++) {
    		Borrow borrow = getDao().get(Borrow.class, Integer.valueOf(totalBorrowIds[i]));
    		borrow.setRePayAmount(borrow.getAmount());
    		getDao().save(borrow);
    	}
    }
    
    if (StringUtils.isNotBlank(reimb.getPartBorrowIds())) {
    	String[] partBorrowIds = reimb.getPartBorrowIds().split(",");
    	for (int i=0; i < partBorrowIds.length; i++) {
    		Borrow borrow = getDao().get(Borrow.class, Integer.valueOf(partBorrowIds[i]));
    		if (reimb.getOffsetAmount() > 0) {
      		borrow.setRePayAmount(borrow.getRePayAmount() + reimb.getOffsetAmount());
      		getDao().save(borrow);
    		}
    	}
    }
    
    if (reimb.getBorrowAmount() != null && reimb.getBorrowAmount() > 0) {
    	RePay rePay = new RePay();
    	rePay.setCreateDate(new Date());
			String singleNo = DateUtil.getDateTime("yyyyMMddHHmmss", rePay.getCreateDate());
			rePay.setSingleNo(RePayConstants.REPAY_SINGLE_PREFIX + singleNo);
			rePay.setTitle("报销还款");
    	rePay.setDept(reimb.getDept());
    	rePay.setAudStatus(FlowConstants.AUDIT_PASS);
    	rePay.setType(RePayConstants.REPAY_TYPE_OFFSET);
    	rePay.setAmount(reimb.getBorrowAmount());
    	rePay.setRePayer(reimb.getReimber());
    	rePay.setAudDate(rePay.getCreateDate());
    	rePay.setAuditor(auditor);
    	rePay.setReimb(reimb);
    	getDao().save(rePay);
    }
	}
	
}
